package ddd.ajava.chapter2.question5;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Calendar;

/**
 * @author lenovo
 * 代理步骤：
 * 1.计算时间
 * 2.获得方法名称
 * 3.取得参数
 */
public class PersonProxy implements InvocationHandler{
	private Object proxy;
	private StringBuilder sb;
	
	public PersonProxy(Object proxy){
		this.proxy=proxy;
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		sb=new StringBuilder();
		method.invoke(this.proxy, args);
		this.calTime();
		sb.append("方法名称:"+method.getName()+";");
		sb.append("参数:"+args[0]);
		sb.append("\n");
		this.outputToTxt();
		return null;
	}
	
	private void outputToTxt(){
		String path=this.getClass().getPackage().getName().replace(".","\\");
		String relativePath="src\\"+path+"\\"+this.getClass().getSimpleName()+".txt";
		try{
			BufferedWriter bw=new BufferedWriter(new FileWriter(relativePath,true));
			bw.write(sb.toString());
			bw.flush();
			bw.close();
		}catch(IOException e){
			e.printStackTrace();
		}
		
	}
	
	private  void calTime(){
		Calendar time=Calendar.getInstance();
		int year=time.get(Calendar.YEAR);
		int month=time.get(Calendar.MONTH)+1;
		int day=time.get(Calendar.DAY_OF_MONTH);
		int hour=time.get(Calendar.HOUR_OF_DAY);
		int min=time.get(Calendar.MINUTE);
		int second=time.get(Calendar.HOUR_OF_DAY);
		String s="时间:"+year+"-"+month+"-"+day+" "+hour+":"+min+":"+second+";";
		sb.append(s);
	}
}
